import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import AuthUtils from '@/utils/AuthUtils'
import ErrorCode from '@/constant/ErrorCode'

// 设置axios全局请求头
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + AuthUtils.getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 响应没有状态码时，则默认为成功状态（200）
    const code = response.data.code || 200
    // 获取自定义错误信息
    const msg = ErrorCode[code] || response.data.msg || ErrorCode['default']

    if (code === 401) {
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
        duration: 3 * 1000
      }).then(() => {
        store.dispatch('user/Logout').then(() => {
          location.href = '/#/login'
        })
      })
    }
    if (code !== 200 && code !== 401) {
      Message({
        message: msg,
        type: 'error',
        duration: 3 * 1000
      })
      return Promise.reject(new Error(msg))
    }
    return response.data
  },
  error => {
    console.log('err' + error) // for debug
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    }
    if (message.includes('timeout')) {
      message = '系统接口请求超时'
    }
    if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
